package packet

type PacketWriter interface {
	Write(b byte)
	WriteShort(s int16)
	WriteUShort(s uint16)
	WriteInt(i int32)
	WriteUInt(i uint32)
	WriteLong(l int64)
	WriteULong(l uint64)
	WriteBool(b bool)
	WriteBytes(b []byte)
	WriteZeroBytes(n int16)
	WritePaddedString(s string, n uint16)
	WriteMapleAsciiString(s string)
	Size() uint16
	GetPacket() []byte
}

func (p *maplePacket) Size() uint16 {
	return uint16(len(*p))
}

func (p *maplePacket) Write(data byte) {
	*p = append(*p, data)
}

func (p *maplePacket) WriteShort(data int16) {
	p.WriteUShort(uint16(data))
}

func (p *maplePacket) WriteUShort(data uint16) {
	*p = append(*p, byte(data), byte(data>>8))
}

func (p *maplePacket) WriteInt(data int32) {
	p.WriteUInt(uint32(data))
}

func (p *maplePacket) WriteUInt(data uint32) {
	*p = append(*p, byte(data), byte(data>>8), byte(data>>16), byte(data>>24))
}

func (p *maplePacket) WriteLong(data int64) {
	p.WriteULong(uint64(data))
}

func (p *maplePacket) WriteULong(data uint64) {
	*p = append(*p, byte(data), byte(data>>8), byte(data>>16), byte(data>>24), byte(data>>32), byte(data>>40), byte(data>>48), byte(data>>56))
}

func (p *maplePacket) WriteBool(b bool) {
	if b {
		p.Write(1)
	} else {
		p.Write(0)
	}
}

func (p *maplePacket) WriteBytes(b []byte) {
	*p = append(*p, b...)
}

func (p *maplePacket) WriteZeroBytes(n int16) {
	for i := int16(0); i < n; i++ {
		p.Write(0)
	}
}

func (p *maplePacket) WritePaddedString(s string, n uint16) {
	gbks := []byte(s)
	length := len(gbks)
	if uint16(length) > n {
		p.WriteBytes(gbks[:n])
	} else {
		p.WriteBytes(gbks)
		p.WriteBytes(make([]byte, length-len(gbks)))
	}
}

func (p *maplePacket) WriteMapleAsciiString(s string) {

	p.WriteUShort(uint16(len(s)))
	p.WriteBytes([]byte(s))
}

func (p *maplePacket) GetPacket() []byte {
	return []byte(*p)
}
